//
//  MessageViewController.m
//  BDD_TWO
//
//  Created by XTW on 2023/11/6.
//

#import "MessageViewController.h"
#import "TabBarView.h"
#import "RefreshErrorAlertView.h"
#import "IQKeyboardManager.h"
#import <WFChatClient/WFCChatClient.h>
#import "MessageTableViewCell.h"
#import "WFCUMessageListViewController.h"
#import "CustomTextAlertView.h"

@interface MessageViewController () {
    TabBarView                 *tabBarView;
    BOOL                       againLoad;
    UIButton                   *messageBtn;
}

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray<WFCCConversationInfo *> *conversations;

@end

@implementation MessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"消息";
    tabBarView = [TabBarView sharedTabBarView];
    [self.navigationItem setHidesBackButton:YES];
    
    messageBtn = [self addRigthBtnImage:[UIImage systemImageNamed:@"plus.message"]];
    [messageBtn addTarget:self action:@selector(toMessageOther) forControlEvents:UIControlEventTouchUpInside];
    againLoad = YES;
    self.conversations = [[NSMutableArray alloc] init];
    self.conversations = [[[WFCCIMService sharedWFCIMService] getConversationInfos:@[@(Single_Type)] lines:@[@(0)]] mutableCopy];
    [self initView];
    
    // Do any additional setup after loading the view from its nib.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.fd_interactivePopDisabled = YES;
    [self.view addSubview:tabBarView];
    [tabBarView setCurrentViewControllerIndex:2];
    if ([UserManger hasUserLogged]) {
        messageBtn.hidden = NO;
        self.tableView.tableFooterView = nil;
        [[IQKeyboardManager sharedManager] setEnable:YES];
        [[IQKeyboardManager sharedManager] setEnableAutoToolbar:YES];
        if (againLoad) {
            againLoad = NO;
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onConnectionStatusChanged:) name:kConnectionStatusChanged object:nil];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onReceiveMessages:) name:kReceiveMessages object:nil];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onRecallMessages:) name:kRecallMessages object:nil];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onDeleteMessages:) name:kDeleteMessages object:nil];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSettingUpdated:) name:kSettingUpdated object:nil];
        }
        
        [self updateConnectionStatus:[WFCCNetworkService sharedInstance].currentConnectionStatus];
        [self refreshList];
        [self updatePcSession];
        [self.tableView reloadData];
    } else {
        messageBtn.hidden = YES;
        self.tableView.tableFooterView = [[RefreshErrorAlertView alloc] initItem:CGRectMake(0, 0, SCREEN_WIDTH_DEVICE, self.tableView.frame.size.height) withType:LoadErrorTypeNoLogin withTip:@"您还没有登录账号" withButtonTitle:@"点击登录" refresh:^(RefreshErrorAlertView * _Nonnull alertView) {
            [[TabBarView sharedTabBarView] actionLogin];
        }];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self popGestureClose:self];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self popGestureOpen:self];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)toMessageOther {
    CustomTextAlertView *alertView = [[CustomTextAlertView alloc] initItem:@"对方ID" withButtons:[NSArray arrayWithObjects:@"取消", @"确定", nil]];
    alertView.SureHandle = ^(NSString * _Nonnull contentStr) {
        if (contentStr.length == 0) {
            [self showHUDAlert:@"输入内容不能为空"];
            return;
        }
        WFCUMessageListViewController *mvc = [[WFCUMessageListViewController alloc] init];
        WFCCConversation *object = [[WFCCConversation alloc] init];
        object.target = contentStr;
        mvc.conversation = object;
        mvc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:mvc animated:YES];
    };
    [alertView backgroundClickDisable];
    [alertView show];
}

- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
    [super traitCollectionDidChange:previousTraitCollection];
    if (@available(iOS 13.0, *)) {
        if ([self.traitCollection hasDifferentColorAppearanceComparedToTraitCollection:previousTraitCollection]) {
            [self.tableView reloadData];
        }
    }
}

- (void)updateConnectionStatus:(ConnectionStatus)status {
//    [self updateTitle];
}

- (void)onConnectionStatusChanged:(NSNotification *)notification {
    ConnectionStatus status = [notification.object intValue];
    [self updateConnectionStatus:status];
}

- (void)onReceiveMessages:(NSNotification *)notification {
    NSArray<WFCCMessage *> *messages = notification.object;
    if ([messages count]) {
        [self refreshList];
    }
}

- (void)onMessageUpdated:(NSNotification *)notification {
    [self refreshList];
}

- (void)onSettingUpdated:(NSNotification *)notification {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self refreshList];
        [self updatePcSession];
    });
}

- (void)onRecallMessages:(NSNotification *)notification {
    [self refreshList];
}

- (void)onDeleteMessages:(NSNotification *)notification {
    [self refreshList];
}


- (void)onClearAllUnread:(NSNotification *)notification {
    if ([notification.object intValue] == 0) {
        [[WFCCIMService sharedWFCIMService] clearAllUnreadStatus];
        [self refreshList];
    }
}

- (void)refreshList {
    self.conversations = [[[WFCCIMService sharedWFCIMService] getConversationInfos:@[@(Single_Type)] lines:@[@(0)]] mutableCopy];
    [self updateBadgeNumber];
    if (self.conversations.count == 0) {
        self.tableView.tableFooterView = [[RefreshErrorAlertView alloc] initItem:self.tableView.frame withType:LoadErrorTypeNoData withTip:@"暂无私信" withButtonTitle:@"联系客服" refresh:^(RefreshErrorAlertView * _Nonnull alertView) {
            WFCUMessageListViewController *mvc = [[WFCUMessageListViewController alloc] init];
            WFCCConversation *object = [[WFCCConversation alloc] init];
            object.target = WFChatCustomer;
            mvc.conversation = object;
            mvc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:mvc animated:YES];
        }];
    }else{
        self.tableView.tableFooterView = nil;
    }
    [self.tableView reloadData];
}

- (void)updateBadgeNumber {
    int count = 0;
    for (WFCCConversationInfo *info in self.conversations) {
        if (!info.isSilent) {
            count += info.unreadCount.unread;
        }
    }
}

- (void)updatePcSession {
    NSArray<WFCCPCOnlineInfo *> *onlines = [[WFCCIMService sharedWFCIMService] getPCOnlineInfos];
    if (@available(iOS 11.0, *)) {
        if (onlines.count) {
//            self.tableView.tableHeaderView = self.pcSessionView;
            if (![[NSUserDefaults standardUserDefaults] boolForKey:@"wfc_uikit_had_pc_session"]) {
                [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"wfc_uikit_had_pc_session"];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
        } else {
            self.tableView.tableHeaderView = nil;
        }
    } else {
    }
}

#pragma mark - UITableView datasource methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.conversations.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"MessageCell";
    MessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"MessageTableViewCell" owner:self options:nil] lastObject];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    cell.info = self.conversations[indexPath.row];
    return cell;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow] animated:YES];
    [[IQKeyboardManager sharedManager] setEnable:NO];
    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:NO];
    
    WFCUMessageListViewController *mvc = [[WFCUMessageListViewController alloc] init];
    WFCCConversationInfo *info = self.conversations[indexPath.row];
    mvc.conversation = info.conversation;
    mvc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:mvc animated:YES];
    
//    WFCCConversation *object = [[WFCCConversation alloc] init];
//    object.target = @"FireRobot";
//    mvc.conversation = object;
        
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (nullable UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath API_AVAILABLE(ios(11.0)) API_UNAVAILABLE(tvos) {
    __weak typeof(self) ws = self;
    UIContextualAction *clearUnread = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleNormal title:@"标为已读" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
        [[WFCCIMService sharedWFCIMService] markAsUnRead:ws.conversations[indexPath.row].conversation syncToOtherClient:YES];
        [ws refreshList];
    }];
    UIContextualAction *delete = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:@"删除" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
        [[WFCCIMService sharedWFCIMService] clearUnreadStatus:ws.conversations[indexPath.row].conversation];
        [ws refreshList];
    }];
//    UIContextualAction *setTop = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleNormal title:@"置顶" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
//        [[WFCCIMService sharedWFCIMService] setConversation:ws.conversations[indexPath.row].conversation top:YES success:^{
//            [ws refreshList];
//        } error:^(int error_code) {
//            [self showHUDAlert:@"更新失败"];
//        }];
//    }];
    UISwipeActionsConfiguration *actions = [UISwipeActionsConfiguration configurationWithActions:[NSArray arrayWithObjects:clearUnread, delete, nil]];
    return actions;
}


- (void)initView {
    [self.tableView setFrame:CGRectMake(0, IS_iPhoneX_Top + NavBarHeight, SCREEN_WIDTH_DEVICE, SCREEN_HEIGHT_DEVICE - IS_iPhoneX_Top - NavBarHeight - TabbarHeight - IS_iPhoneX_Bottom)];
    
}
@end
